package com.zhongwang.mms.module.material.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhongwang.mms.base.BaseController;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.MChangeOrder;
import com.zhongwang.mms.gen.entity.MMaterialDictionary;
import com.zhongwang.mms.gen.entity.MMaterials;
import com.zhongwang.mms.gen.entity.TDept;
import com.zhongwang.mms.module.basic.dao.MMaterialDictionaryDao;
import com.zhongwang.mms.module.basic.dao.MMaterialsDao;
import com.zhongwang.mms.module.basic.dao.TWarehouseInfoDao;
import com.zhongwang.mms.module.basic.service.MMaterialDictionaryService;
import com.zhongwang.mms.module.basic.service.TDeptService;
import com.zhongwang.mms.module.material.dao.MChangeOrderDao;
import com.zhongwang.mms.module.material.dao.MOrderDetailDao;
import com.zhongwang.mms.module.material.model.MChangeOrderModel;
import com.zhongwang.mms.module.material.model.MProCodeQueryModel;
import com.zhongwang.mms.module.material.model.MProject;
import com.zhongwang.mms.module.material.service.MChangeOrderService;
import com.zhongwang.mms.util.ShiroUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 串料管理 控制层
 * @Author: China.wsg
 * @Date: 2020/04/13 09:57
 */
@Controller
@RequestMapping("/material/changeOrder")
public class MChangeOrderController extends BaseController {

    @Autowired
    private TDeptService deptService;
    @Autowired
    private MMaterialDictionaryService mMaterialDictionaryService;
    @Autowired
    private MChangeOrderService mchangeOrderService;
    @Autowired
    private MChangeOrderDao mChangeOrderDao;
    @Autowired
    private MMaterialsDao mMaterialsDao;
    @Autowired
    private MMaterialDictionaryDao mMaterialDictionaryDao;
    @Autowired
    private MOrderDetailDao orderDetailDao;
    @Autowired
    private TWarehouseInfoDao tWarehouseInfoDao;

    /**
     * 串料申请列表 页面
     *
     * @return 页面路径
     */
    @GetMapping("/page")
    @RequiresPermissions({"matinv:matchalist:view"})
    public String page() {

        return "material/matWarManage/ChangeOrder/list";
    }

    /**
     * 创建入库单页面
     *
     * @param model
     * @return
     */
    @GetMapping("/create")
    @RequiresPermissions({"matinv:matchalist:edit"})
    public String create(Model model) {
        // 获取登入用户实体
        model.addAttribute("matType", mMaterialDictionaryService.findMaterialDictionaryByKindName("").getMaterialTypeList());
        model.addAttribute("matQuality", mMaterialDictionaryService.findMaterialDictionaryByKindName("").getMaterialQualityList());
        model.addAttribute("matSpec", mMaterialDictionaryService.findMaterialDictionaryByKindName("").getMaterialSpecList());
        model.addAttribute("userName", ShiroUtils.getUser().getName());
        model.addAttribute("dept", deptService.findDeptInfo(new TDept()));
        model.addAttribute("warehouse", tWarehouseInfoDao.findWarehouseInfoListByWhiType("原料库"));
        return "material/matWarManage/ChangeOrder/create";
    }

    /**
     * 保存串料申请单
     *
     * @param changeOrder 保存信息
     * @return json 数据
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions({"matinv:matchalist:edit"})
    public JsonResult save(MChangeOrder changeOrder) {
        return jsonResult(mchangeOrderService.saveChangeOrder(changeOrder));
    }

    /**
     * 串料申请列表
     *
     * @param changeOrderModel 查询条件
     * @return list
     */
    @ResponseBody
    @PostMapping("/list")
    @RequiresPermissions(value = {"matinv:matchalist:view","matinv:matexeccha:view"}, logical = Logical.OR)
    public JsonResult list(MChangeOrderModel changeOrderModel) {
        if (changeOrderModel.getCeoPageFlgQuery() == 2) {
            // 串料执行列表页面 状态检索条件需要 特殊处理一下
            if (changeOrderModel.getCeoStatus() == null) {
                // 全部
                changeOrderModel.setCeoCheckStatusListQuery(Arrays.asList(2, 3, 4, 5, 6));
            } else if (changeOrderModel.getCeoStatus() == 2) {
                // 未执行
                changeOrderModel.setCeoCheckStatusListQuery(Arrays.asList(2));
            } else if (changeOrderModel.getCeoStatus() == 3) {
                // 已执行
                changeOrderModel.setCeoCheckStatusListQuery(Arrays.asList(3, 4, 5, 6));
            }
            changeOrderModel.setCeoStatus(null);
        }
        startPage();
        List<MChangeOrder> list = mchangeOrderService.findMChangeOrderByQuery(changeOrderModel);
        return jsonResult(list);
    }

    /**
     * 修改串料申请状态
     *
     * @param changeOrder 修改信息
     * @return json 数据
     */
    @ResponseBody
    @PostMapping("/updateStatus")
    @RequiresPermissions(value = {"matinv:matchalist:edit","matinv:matexeccha:edit"}, logical = Logical.OR)
    public JsonResult updateStatus(MChangeOrder changeOrder) {
        return jsonResult(mchangeOrderService.updateStatus(changeOrder));
    }

    /**
     * 串料申请单 页面
     *
     * @param ceoId
     * @param model
     * @return 页面路径
     */
    @GetMapping("/view/{ceoId}")
    @RequiresPermissions({"matinv:matchalist:view"})
    public String view(@PathVariable("ceoId") Integer ceoId, Model model) {
        model.addAttribute("changeOrder", mChangeOrderDao.selectByPrimaryKey(ceoId));
        return "material/matWarManage/ChangeOrder/view";
    }

    /**
     * 串料申请单修改 页面
     *
     * @param ceoId
     * @param model
     * @return 页面路径
     */
    @GetMapping("/edit/{ceoId}")
    @RequiresPermissions({"matinv:matchalist:edit"})
    public String edit(@PathVariable("ceoId") Integer ceoId, Model model) {
        model.addAttribute("matType", mMaterialDictionaryService.findMaterialDictionaryByKindName("").getMaterialTypeList());
        model.addAttribute("matQuality", mMaterialDictionaryService.findMaterialDictionaryByKindName("").getMaterialQualityList());
        model.addAttribute("matSpec", mMaterialDictionaryService.findMaterialDictionaryByKindName("").getMaterialSpecList());
        model.addAttribute("dept", deptService.findDeptInfo(new TDept()));

        MChangeOrder changeOrder = mChangeOrderDao.selectByPrimaryKey(ceoId);
        model.addAttribute("changeOrder", changeOrder);

        MMaterials materials = mMaterialsDao.selectByPrimaryKey(changeOrder.getCeoNeedMatId());
        model.addAttribute("material", materials);

        MMaterialDictionary materialDictionary = mMaterialDictionaryDao.selectByPrimaryKey(materials.getMatSpecId());
        model.addAttribute("materialDictionary", materialDictionary);
        return "material/matWarManage/ChangeOrder/update";
    }

    /**
     * 串料申请单修改 页面
     *
     * @param ceoId
     * @param model
     * @return 页面路径
     */
    @GetMapping("/editOther/{ceoId}")
    @RequiresPermissions({"matinv:matchalist:edit"})
    public String editOther(@PathVariable("ceoId") Integer ceoId, Model model) {
        model.addAttribute("changeOrder", mChangeOrderDao.selectByPrimaryKey(ceoId));
        return "material/matWarManage/ChangeOrder/updateOther";
    }

    /**
     * 修改串料申请单
     *
     * @param changeOrder 保存信息
     * @return json 数据
     */
    @ResponseBody
    @PostMapping("/edit")
    @RequiresPermissions({"matinv:matchalist:edit"})
    public JsonResult edit(MChangeOrder changeOrder) {
        return jsonResult(mchangeOrderService.editChangeOrder(changeOrder));
    }

    /**
     * 被执行后的串料申请修改
     * 暂定可以修改内容：计划归还编码
     *
     * @param changeOrder 保存信息
     * @return json 数据
     */
    @ResponseBody
    @PostMapping("/editOther")
    @RequiresPermissions({"matinv:matchalist:edit"})
    public JsonResult editOther(MChangeOrder changeOrder) {
        return jsonResult(mChangeOrderDao.updateByPrimaryKeySelective(changeOrder));
    }

    /**
     * 串料申请执行（审核） 页面
     *
     * @return 页面路径
     */
    @GetMapping("/check")
    @RequiresPermissions({"matinv:matexeccha:view"})
    public String checkList() {

        return "material/matWarManage/ChangeOrder/check";
    }

    /**
     * 串料申请执行（单条执行）
     *
     * @param ceoId 申请Id
     * @return
     */
    @ResponseBody
    @PostMapping("/checkSingle")
    @RequiresPermissions({"matinv:matexeccha:edit"})
    public JsonResult checkSingle(Integer ceoId) {

        JsonResult jsonResult = new JsonResult();
        String msg = mchangeOrderService.checkSingle(ceoId);
        if (!msg.contains("执行失败")) {
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
        }
        jsonResult.setMsg(msg);
        return jsonResult;
    }

    /**
     * 串料申请执行（批量执行）
     *
     * @param arr 申请Id集合
     * @return
     */
    @ResponseBody
    @PostMapping("/checkTogether")
    @RequiresPermissions({"matinv:matexeccha:edit"})
    public JsonResult checkTogether(@RequestBody List<Integer> arr) {

        JsonResult jsonResult = new JsonResult();
        String msg = mchangeOrderService.checkTogether(arr);
        if (!msg.contains("执行失败")) {
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
        }
        jsonResult.setMsg(msg);
        return jsonResult;
    }

    /**
     * 撤销被执行串料（单条执行）
     *
     * @param ceoId 申请Id
     * @return
     */
    @ResponseBody
    @PostMapping("/cancelSingle")
    @RequiresPermissions({"matinv:matexeccha:edit"})
    public JsonResult cancelSingle(Integer ceoId) {

        JsonResult jsonResult = new JsonResult();
        String msg = mchangeOrderService.cancelSingle(ceoId);
        if (!msg.contains("执行失败")) {
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
        }
        jsonResult.setMsg(msg);
        return jsonResult;
    }

    /**
     * 项目编码存在校验（共通方法，多页面调用）
     * 页面级校验
     *
     * @param param
     * @return
     */
    @PostMapping("/codeExist")
    @ResponseBody
    public String codeExist(MProCodeQueryModel param) {
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("valid", mchangeOrderService.codeExist(param));
        String resultString = "";
        ObjectMapper mapper = new ObjectMapper();
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
    }

    /**
     * 根据项目编号取得项目信息（共通方法，多页面调用）
     *
     * @param proCode 项目编号
     * @return
     */
    @ResponseBody
    @GetMapping("/findProject")
    public JsonResult findProjectByProCode(String proCode) {

        JsonResult jsonResult = new JsonResult();
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
        jsonResult.setData(orderDetailDao.findProjectBySALEProCode(proCode));
        return jsonResult;
    }


}
